package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.AsyncContext;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AsyncServletTest extends GenericServlet {

    private static final long serialVersionUID = 201706230001L;

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html;charset=UTF-8");
        PrintWriter out = res.getWriter();
        out.println("进入Servlet的时间：" + new Date() + ".");
        out.flush();
        //在子线程中执行业务调用，并由其负责输出响应，主线程退出
        final AsyncContext ctx = req.startAsync();
        ctx.start(new Runnable() {
            public void run() {
                HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
                System.out.println(request.getAttribute("ming"));
                HttpServletResponse response =  (HttpServletResponse) ctx.getResponse();
                try {
                    Thread.sleep(10000);
                    response.getWriter().println("hahahahaha");
                    ctx.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        out.println("结束Servlet的时间：" + new Date() + ".");
        out.flush();
    }
	

}
